import 'package:flutter/material.dart';
import 'eventBus.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
      routes: <String, WidgetBuilder> {
        'login_page': (context)=>LoginRoute(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _state = '暂未登录';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    bus.add('login', (arg) {
      setState(() {
        _state = arg ?? '';
        //移除
        // EventCallback f = (arg){};
        // bus.remove('login', f);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.center,
        child: FlatButton(
          color: Colors.blue,
          child: Text(
            _state,
            style: TextStyle(fontSize: 23, color: Colors.white)
          ),
          onPressed: () {
            setState(() {
              _state = '暂未登录';
            });
            Navigator.pushNamed(context, 'login_page');
          },
        ),
      ),
    );
  }
}

class LoginRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('登录'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: FlatButton(
          color: Colors.blue,
          child: Text('登录', style: TextStyle(color: Colors.white,)),
          onPressed: () {
            bus.emit('login', 'userModel: 小明');
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}
